//
//  WBTitleButton.swift
//  weibo
//
//  Created by iobit on 2017/07/04.
//  Copyright © 2017 zhuxu. All rights reserved.
//

import UIKit

class WBTitleButton: UIButton {

    init(title: String?) {
        
        super.init(frame: CGRect())
        // title为空则显示为首页
        if title == nil {
            setTitle("首页", for: .normal)
        }else {
            setTitle(title! + " ", for: .normal)
            
            setImage(UIImage(named: "navigationbar_arrow_down"), for: UIControlState.normal)
            
            setImage(UIImage(named: "navigationbar_arrow_up"), for: .selected)
        }
        
        titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        
        setTitleColor(UIColor.darkGray, for: .normal)
        
        sizeToFit()
        

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // 重新布局子视图
    override func layoutSubviews() {
        super.layoutSubviews()
//        print("执行次数")
        // 判断label和image是否同时存在
        guard let titleLabel = titleLabel,
            let imageView = imageView
            else {
            return
        }
//        print("移动前\(self.titleLabel)")
//        print("移动前\(self.imageView)")
        //会执行两次，暂时解决办法，让其中一次不移动
        if (self.tag == 20) {
            titleLabel.frame = titleLabel.frame.offsetBy(dx: -imageView.bounds.size.width, dy: 0)
//            print("移动后\(titleLabel.frame)")
            imageView.frame = imageView.frame.offsetBy(dx: titleLabel.bounds.size.width, dy: 0)
//            print("移动后\(imageView.frame)")
            
        }
        self.tag = 20
    }
    
}
